# coding: utf-8
import os
import sys
import imp
import sqlite3
import csv
import xlrd
import uuid
import simplejsion
import jinja2
import werkzeug.utils
from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp import SUPERUSER_ID
import web
form render import render
from Dao import Dao

import logging
_logger = logging.getLogger(__name__)

loader = jinja2.packageLoader('openerp.addons.eroad_bracelet_import','mywebpage')
env = jinja2.Environment(loader=loader, autoescape=True)
env.filters["json"] = simplejsion.dumps

#标题F0002    分类F0003  标题分词F0004  内容F0005 URL F0006
def getDreamId(req, mF0002, mF0003, mF0004, mF0005, mF0006):
    registry = req.registry
    sa_obj = registry.get('eroad.bracelet.dream')
    # firstly  if the title is repeat
    mTitle = mF0002.replace('梦见','')
    ids = sa_obj.search(req.cr ,SUPERUSER_ID,[('title','=',mTitle)])
    if len(ids)>0:
        return None
    else:
        vals ={
            'title':mTitle,
            'class':mF0003,
            'context':mF0005,
            'source_url':mF0006,
            'title_cut':mF0004,
            'viewcount':0,
        }
        ret = sa_obj.create(req.cr, SUPERUSER_ID,vals)
        return ret
    


class importdream(http.Controller):
    def rootPath(self):
        stock_obj = sys.modules['openerp.addons.eroad_bracelet_import']
        retrun ('%s') %(os.path.dirname(stock_obj.__file__))
    
    #test page
    @http.route(['/hz/myweb/uploaddream'], type='http', auth = 'none')
    def hz_myweb_upload(self, req, **kw):
        method = req.httprequest.method
        if method =="POST":
            filename = kw["myfile"].filename
            if filename<>'':
                data = kw["myfile'].stream.read()
                xlsfilename = '%s/uploadFile/%s' %(self.rootPath(),filename)
                self.createDir('%s/uploadFile/%s' %(self.rootPath()))
                dbname = '%s/controllers/temp/importdream.db' %(self.rootPath())
                self.createDir('%s/controllers/temp' %(self.rootPath))
                
                WriteFileData = open(xlsfilename,'wb')
                WriteFileData.write(data)
                WriteFileData.close()
                dao = Dao(dbname)
                dao.importDream2Excel(xlsfilename)
                _logger.info('周公解梦从excel导入本地临时库 完毕！')
                self.importdata(req,dao)
                _logger.info('周公解梦从临时库导入系统完毕！')
            
        try:
            html = env.get_template('uploaddream.html').render()
        except:
            html ='error'
        return html
    
    def createDir(self,mPath):
        if os.path.isdir(mPath):
            pass
        else:
            os.mkdir(mPath)
        
    def importdata(self, req, dao):
        queryList = dao.query('select * from T0007')
        for row in queryList:
            v_dr_id = getDreamId(req, '%s' %(row['F0002']), '%s' %(row['F0003']), '%s'%(row['F0004']), '%s' %(row['F0005']), '%s' %(row['F0006']))
            if v_dr_id:
                _logger.info('导入成功第一笔：%s' %[row['F0002'], row['F0003'], row['F0004']])
            else:
                _logger.info('导入失败一笔，原因标题已存在：%s' %row['F0002'])
        return 
            
            

































